package com.mike.bdb.ui.provider.table;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;

import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.TableViewer;

import com.mike.bdb.util.DataCurrent;
import com.mike.bdb.util.ReflectUtil;

public class MikeTableCellModifier implements ICellModifier {

	private TableViewer tableViewer;
	private HashMap<String, Type> types;
	public MikeTableCellModifier(TableViewer tableViewer, HashMap<String, Type> types) {
		this.tableViewer = tableViewer;
		this.types = types;
	}

	@Override
	public boolean canModify(Object obj, String property) {
		
		Field notModifyField = null;
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		notModifyField = ReflectUtil.getPKFieldByStoreClassName(curStoreClazz);
		
		if(null != notModifyField && notModifyField.getName().toLowerCase().contains(property.replace("get", "").toLowerCase())) {
			//主键不允许修改
			return false;
		} else {
			return true;
		}
	}

	@Override
	public Object getValue(Object element, String property) {
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		return ReflectUtil.invokeGet(curStoreClazz, property, element);
	}

	@Override
	public void modify(Object element, String property, Object value) {
		if(element instanceof org.eclipse.swt.widgets.Item) {
			element = ((org.eclipse.swt.widgets.Item) element).getData();
		}
		
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		ReflectUtil.invokeSet(curStoreClazz, property, element, value, types);
		
	    tableViewer.refresh();
	}

}
